package org.mqlink4sap;

import java.io.FileNotFoundException;
import java.util.ResourceBundle;

import org.mqlink4sap.configuration.Configuration;
import org.mqlink4sap.configuration.LinkDefinition;
import org.mqlink4sap.exceptions.ConnectorInitializationException;
import org.mqlink4sap.globals.Worker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sampullara.cli.Args;

public class ConsoleApplication {

	private static Logger log = LoggerFactory
			.getLogger(ConsoleApplication.class);
	private static ResourceBundle rb = ResourceBundle
			.getBundle("org.mqlink4sap.i18n.text");

	private static final String TG_NAME_WORKERS = "Workers";
	private static final long MAIN_THREAD_SLEEP_INTERVAL = 1000L;

	public static void main(String[] args) throws FileNotFoundException {

		log.info(rb.getString("Start"), "ConsoleApplication");

		// Parse arguments
		try {
			Args.parse(CLIArguments.class, args);
		} catch (IllegalArgumentException e) {
			Args.usage(CLIArguments.class);
			System.exit(1);
			return;
		}

		log.info(rb.getString("ConfigFileName"),
				CLIArguments.getConfigFileName());

		// Load configuration file
		Configuration config = Configuration.load(CLIArguments
				.getConfigFileName());

		log.debug(rb.getString("ConfigurationDebugPrint"), config.toString());
		
		// Create and start workers
		ThreadGroup g = new ThreadGroup(TG_NAME_WORKERS);
		try {
			log.info(rb.getString("StartingWorkers"));
			for (LinkDefinition d : config.Links) {
				log.info(rb.getString("StartingSingleWorker"), d.Queue, d.From,
						d.To);
				new Thread(g, Worker.getWorker(d, config.Systems)).start();
			}
		} catch (ConnectorInitializationException e1) {
			log.error(rb.getString("WorkerInitializationFailed"), e1.getCause());
		}

		// Do nothing while workers are active
		try {
			while (g.activeCount() > 0)
				Thread.sleep(MAIN_THREAD_SLEEP_INTERVAL);
			log.warn(rb.getString("AboutToTerminate"), config.Links.size());
		} catch (InterruptedException e) {
			log.error(rb.getString("MainThreadInterrupted"));
		} finally {
			if (g.activeCount() > 0) {
				log.warn(rb.getString("ForceTerminatingWorkThreads"),
						g.activeCount());
				g.interrupt();
			}
		}

		log.info(rb.getString("Finish"));

	}
}
